import React, { useEffect, useState } from 'react';
import {
  Trigger,
  Badge,
  Button, List, Result, Typography, Tag, Grid
} from '@arco-design/web-react';
import useLocale from '../../utils/useLocale';
import instance from '@/utils/request';
import { MessageResponse } from '@/constants/type';
import { IconRefresh } from '@arco-design/web-react/icon';

const { Row, Col } = Grid;

const DropContent = (props: { unreadMessage: MessageResponse[], refresh: () => void }) => {
  const t = useLocale();

  function readMessage(data: MessageResponse[]) {
    const ids = data.map((item) => item.id);
    instance
      .post('/api/message/updateBatch', {
        ids: ids,
        readState: true
      })
      .then(() => {
        props.refresh();
      });
  }

  return (
    <Row style={{
      width: '300px',
      maxHeight: '400px',
      backgroundColor: 'var(--color-bg-popup)',
      border: '1px solid var(--color-border-2)',
      boxShadow: '@shadow2-down',
      borderRadius: '@border-radius-medium'
    }} justify={'space-between'} align={'center'}>
      <List
        style={{ width: '300px' }}
        noDataElement={<Result status="404" subTitle={t['message.empty.tips']} />}
        footer={
          <Row justify={'space-around'} align={'center'}>
            <Button type="text" size="small" onClick={() => readMessage(props.unreadMessage)}>
              {t['message.allRead']}
            </Button>
            <Button type="text" size="small">
              {t['message.seeMore']}
            </Button>
          </Row>
        }
      >
        {props.unreadMessage.map((item, index) => (
          <List.Item
            key={item.id}
            actionLayout="vertical"
            style={{
              opacity: !!item.readState ? 0.5 : 1,
              width: '100%'
            }}
          >
            <Row
              style={{ cursor: 'pointer' }}
              onClick={() => readMessage([item])}>
              <List.Item.Meta
                title={
                  <Row style={{ fontSize: '.9rem' }} align={'center'} justify={'space-between'}>
                    <Typography.Text>{item.content}</Typography.Text>
                    {item.type && item.type.name ? (
                      <Tag style={{ marginLeft: '0.5rem' }}>{item.type.name}</Tag>
                    ) : null}
                  </Row>
                }
              />
            </Row>
          </List.Item>
        ))}
      </List>
    </Row>
  );
};

const MessageBox = ({ children }) => {
  const [loading, setLoading] = useState(false);
  const [unreadMessages, setUnreadMessages] = useState([]);
  const [unreadMessageCount, setUnreadMessageCount] = useState(0);

  function fetchMessageData(showLoading = true) {
    showLoading && setLoading(true);
    instance
      .post('/api/message/page', { query: { readState: false }, pager: { pageSize: 5, pageNumber: 1 } })
      .then((res) => {
        if (res.data.code === 200) {
          setUnreadMessages(res.data.data);
          setUnreadMessageCount(res.data.total);
        }
      })
      .finally(() => {
        showLoading && setLoading(false);
      });
  }

  useEffect(() => {
    fetchMessageData();
  }, []);
  return (
    <Trigger
      trigger="hover"
      popup={() => <DropContent refresh={fetchMessageData} unreadMessage={unreadMessages} />}
      position="br"
      unmountOnExit={false}
      popupAlign={{ bottom: 4 }}
    >
      <Badge count={loading ? (<IconRefresh style={{ color: 'red' }} spin />) : (unreadMessageCount)}>
        {children}
      </Badge>
    </Trigger>
  );
};

export default MessageBox;
